﻿using Microsoft.AspNetCore.Mvc;

namespace PdfWeb.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PdfSyncController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public PdfSyncController(IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClientFactory.CreateClient();
        }
        /// <summary>
        /// 请求wcf服务下载pdf并保存到本地`
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        /// <remarks> add by cfl 23:51 2025年11月5日</remarks>
        [HttpGet("download/{fileName}")]
        public async Task<IActionResult> DownloadPdf(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return BadRequest("文件名不能为空");

            // 调用 WCF 服务的 GetPdfStream 接口
            string wcfUrl = $"http://localhost:58174/PdfShareService/GetPdfUrl?fileName={fileName}";

            var response = await _httpClient.GetAsync(wcfUrl);
            if (!response.IsSuccessStatusCode)
                return StatusCode((int)response.StatusCode, "WCF 服务访问失败");

            var stream = await response.Content.ReadAsStreamAsync();

            // 将下载的 PDF 同步保存到本地某个路径（比如 wwwroot/pdf）
            string savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "pdf", fileName);
            Directory.CreateDirectory(Path.GetDirectoryName(savePath));
            using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
            {
                await stream.CopyToAsync(fileStream);
            }

            return Ok(new { message = "下载成功", filePath = savePath });
        }
    }
}
